package net.toocruel.iqismart.service.core.impl;

import net.toocruel.iqismart.dao.UserRepository;
import net.toocruel.iqismart.dao.core.MessageRepository;
import net.toocruel.iqismart.entity.core.Message;
import net.toocruel.iqismart.service.core.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description
 * @Auther sty
 * @createTime 2018/5/21 下午5:34
 */
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageRepository messageRepository;

    @Autowired
    private UserRepository userRepository;
    @Override
    public void send(Long fromUserId, Long toUserId, String content) {
        Message message = new Message();
        message.setFromUser(userRepository.findOne(fromUserId));
        message.setToUser(userRepository.findOne(toUserId));
        message.setContent(content);
        messageRepository.save(message);
    }

    @Override
    public void read(Long messageId) {
        Message message = messageRepository.findOne(messageId);
        message.setRead(true);
        messageRepository.save(message);
    }

    @Override
    public void read(Long[] messageIds) {
        List<Message> messages = messageRepository.findAll((root, query, cb) -> cb.in(root.get("id").in(messageIds)));
        messages.forEach(message -> message.setRead(true));
        messageRepository.save(messages);
    }

    @Override
    public List<Message> findByToUser(Long id) {
        return messageRepository.findAll((root, query, cb) -> {
            return cb.and(cb.equal(root.get("toUser"),id),cb.isFalse(root.get("read")));
        });
    }

    @Override
    public Page<Message> findALl(Long id, PageRequest pageRequest) {
        return messageRepository.findAll((root, query, cb) -> {
            return cb.equal(root.get("toUser"),id);
        },pageRequest);
    }
}
